<?php

namespace app\admin\controller;

use app\admin\controller\CommonController;
use think\Validate;
use think\Db;
use app\util\Utils;
use app\admin\model\StoreTixian;
use app\admin\model\StaffTixian;
use app\admin\model\VenderTixian;
use app\admin\model\Store;
use app\admin\model\Staff;
use app\admin\model\StoreFlow;
use app\admin\model\StaffFlow;
use app\admin\model\ProvCityArea;
use app\admin\model\VenderFlow;
use app\admin\model\Order;
use app\admin\model\StoreFlowCopy;
use app\admin\model\StaffFlowCopy;
use app\admin\model\CtmTixian;
use app\admin\model\Custom;
use app\admin\model\CtmFlow;
use app\admin\model\StaffFlowNew;

class FinanceController extends CommonController {
    /*
     * 店铺提现列表
     * author xfwed 
     * date 2019.09.25
     */

    public function storeTixianList() {
        $type = input('param.type');
        $store_name = input('param.store_name');
        $phone = input('param.phone');
        $ali_id = input('param.ali_id');
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');
        $store_id = input('param.store_id');
        $store_type = input('param.store_type');//店铺类型 0全部 1品牌连锁店 2服务授权店

        $perPage = input('param.perPage');
        $page = input('param.page');

        if ($store_id) {
            $where['t.store_id'] = $store_id;
        }
        if ($store_name) {
            $where['s.store_name'] = ['like', '%' . $store_name . '%'];
        }

        if ($phone) {
            $where['s.keeper_phone'] = $phone;
        }

        if ($ali_id) {
            $where['t.ali_id'] = $ali_id;
        }
        if ($end_time && $start_time) {
            if ($type == 0) {
                $where['t.ctime'] = array('between', array($start_time, $end_time));
            } elseif ($type == 1) {
                $where['t.stime'] = array('between', array($start_time, $end_time));
            } elseif ($type == 2) {
                $where['t.utime'] = array('between', array($start_time, $end_time));
            }
        } elseif (empty($end_time) && $start_time) {
            $time = strtotime($start_time);
            $time2 = $time + 24 * 60 * 60;
            $time2 = date('Y-m-d H:i:s', $time2);
            if ($type == 0) {
                $where['t.ctime'] = array('between', array($time, $time2));
            } elseif ($type == 1) {
                $where['t.stime'] = array('between', array($time, $time2));
            } elseif ($type == 2) {
                $where['t.utime'] = array('between', array($time, $time2));
            }
        }
        if ($type == 0) {
            $order = 't.ctime asc';
        } elseif ($type == 1) {
            $order = 't.stime asc';
        } elseif ($type == 2) {
            $order = 't.utime desc';
        }
        
        if($store_type){
            $where['s.type'] = $store_type;
        }

        $where['t.status'] = $type;
        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        $list = StoreTixian::alias('t')
                ->join('store s', 's.id = t.store_id')
                ->field('t.*,s.store_name,s.keeper_phone,s.type store_type')
                ->order($order)
                ->where($where)
                ->paginate($perPage);

        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 美容师提现列表
     * author xfwed 
     * date 2019.09.26
     */

    public function staffTixianList() {
        $type = input('param.type');
        $staff_name = input('param.staff_name');
        $phone = input('param.phone');
        $ali_id = input('param.ali_id');
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');
        $staff_id = input('param.staff_id');
        $staff_type = input('param.staff_type');//美容师类型 0全部 1品牌连锁店 2服务授权店

        $perPage = input('param.perPage');
        $page = input('param.page');
        if ($staff_id) {
            $where['t.staff_id'] = $staff_id;
        }

        if ($staff_name) {
            $where['s.staff_name'] = ['like', '%' . $staff_name . '%'];
        }

        if ($phone) {
            $where['s.telephone'] = $phone;
        }

        if ($ali_id) {
            $where['t.ali_id'] = $ali_id;
        }
        if ($end_time && $start_time) {
            if ($type == 0) {
                $where['t.ctime'] = array('between', array($start_time, $end_time));
            } elseif ($type == 1) {
                $where['t.stime'] = array('between', array($start_time, $end_time));
            } elseif ($type == 2) {
                $where['t.utime'] = array('between', array($start_time, $end_time));
            }
        } elseif (empty($end_time) && $start_time) {
            $time = strtotime($start_time);
            $time2 = $time + 24 * 60 * 60;
            $time2 = date('Y-m-d H:i:s', $time2);
            if ($type == 0) {
                $where['t.ctime'] = array('between', array($time, $time2));
            } elseif ($type == 1) {
                $where['t.stime'] = array('between', array($time, $time2));
            } elseif ($type == 2) {
                $where['t.utime'] = array('between', array($time, $time2));
            }
        }
        if ($type == 0) {
            $order = 't.ctime asc';
        } elseif ($type == 1) {
            $order = 't.stime asc';
        } elseif ($type == 2) {
            $order = 't.utime desc';
        }
        if($staff_type){
            $where['s.type'] = $staff_type;
        }

        $where['t.status'] = $type;
        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        $list = StaffTixian::alias('t')
                ->join('staff s', 's.id = t.staff_id')
                ->join('prov_city_area p','p.id = s.city','left')
                ->field('t.*,s.staff_name,s.telephone,s.type staff_type,p.merger_name')
                ->order($order)
                ->where($where)
                ->paginate($perPage);

        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 生成批次号
     * author xfwed
     * date 2019-09-25
     * */

    public function batch() {
        $id = input('param.id');
        $type = input('param.type'); //1店铺2美容师
        $sadmin = input('param.sadmin');

        if ($type == 1) {
            $tixian = new StoreTixian();
            $find = StoreTixian::where("id=" . $id)->find();
            $note = '无人加盟店提现';
        } elseif ($type == 2) {
            $tixian = new StaffTixian();
            $find = StaffTixian::where("id=" . $id)->find();
            $note = '美容师提现';
        }

        $batch = Utils::generateTixianNum($type);

        $detail = date('Ymdhis', time()) . '^' . $find['ali_id'] . '^' . $find['ali_name'] . '^' . $find['money'] / 100 . '^' . $note;
        $data['batch'] = $batch;
        $data['sadmin'] = $sadmin;
        $data['status'] = 1;
        $data['stime'] = date('Y-m-d H:i:s');
        $data['detail'] = $detail;

        $row = $tixian->where('id', '=', $id)->find();
        if ($row['status'] == 1) {
            return Utils::ajaxReturn(3, '已经生成批次', null);
        }

        $result = $tixian->where('id', '=', $id)->update($data);
        if ($result) {
            return Utils::ajaxReturn(0, "生成批次成功,金额为" . $find['money'] / 100 . "元", null);
        } else {
            return Utils::ajaxReturn(3, '生成批次失败', null);
        }
    }

    /*
     * 取消批次号
     * author xfwed
     * date 2019-09-25
     * */

    public function cancel() {
        $id = input('param.id');
        $type = input('param.type');
        if ($type == 1) {
            $tixian = new StoreTixian();
        } elseif ($type == 2) {
            $tixian = new StaffTixian();
        }
        $row = $tixian->where('id', '=', $id)->find();
        $onetime = date('Y-m-d H:i:s', strtotime(date("Y-m-d"), time()));
        if ($row['stime'] > $onetime) {
            return Utils::ajaxReturn(3, '只能取消昨天及以前的单', '');
        }

        $data['batch'] = '';
        $data['status'] = 0;

        $result = $tixian->where('id', '=', $id)->update($data);
        if ($result) {
            return Utils::ajaxReturn(0, "取消批次成功", '');
        } else {
            return Utils::ajaxReturn(3, '取消批次失败', '');
        }
    }

    /*
     * 退回
     * author xfwed
     * date 2019-09-25
     * */

    public function back() {
        $id = input('param.id');
        $type = input('param.type');
        if ($type == 1) {
            $tixian = new StoreTixian();
        } elseif ($type == 2) {
            $tixian = new StaffTixian();
        }
        $find = $tixian->where("id=" . $id)->find();
        Db::startTrans(); //开启事务
        if ($type == 1) {
            $storeRow = Store::where('id', $find['store_id'])->field('money,tx_money,keeper_phone')->find();
            $telephone = $storeRow['keeper_phone'];
            $money = [
                'money' => $storeRow['money'] + $find['money'] + $find['poundage'],
                'tx_money' => $storeRow['tx_money'] - $find['money'] - $find['poundage'],
            ];
            $result = Store::where('id', $find['store_id'])->update($money);
        } elseif ($type == 2) {
            $staffRow = Staff::where('id', $find['staff_id'])->field('money,tx_money,can_txmoney,telephone')->find();
            $telephone = $staffRow['telephone'];
            $money = [
                'money' => $staffRow['money'] + $find['money'] + $find['poundage'],
                'tx_money' => $staffRow['tx_money'] - $find['money'] - $find['poundage'],
                'can_txmoney' => $staffRow['can_txmoney'] + $find['money'] + $find['poundage'],
            ];
            $result = Staff::where('id', $find['staff_id'])->update($money);
        }
        $data = [
            'status' => 3,
        ];
        $tixianResult = $tixian->where('id', '=', $id)->update($data);
        if ($result && $tixianResult) {
            Db::commit();
            $content = "温馨提示：由于您提供的支付宝账号有误，导致提现失败，请及时联系客服，提供正确的支付宝账号，重新提现，谢谢配合！如有疑问请联系客服 电话：4008013680";
            $sendResult = Utils::sendSms($telephone, $content);
            return Utils::ajaxReturn(0, "退回成功", '');
        } else {
            Db::rollback(); //事务回滚
            return Utils::ajaxReturn(3, '退回失败', '');
        }
    }

    /*
     * 店铺/美容师财务汇总
     * author xfwed
     * date 2019-09-26
     * */

    public function financeInfo() {
        $type = input('param.type'); //1店铺2美容师
        $id = input('param.id'); //店铺id/美容师id
        $beginTime = date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), 1, date("Y"))); //本月开始时间
        $endTime = date("Y-m-d H:i:s", mktime(23, 59, 59, date("m"), date("t"), date("Y"))); //本月结束时间
        if ($type == 1) {
            $flowModel = new StoreFlow();
            $flowcopyModel = new StoreFlowCopy();
            $model = new Store();
            $tixianModel = new StoreTixian();
            $where['store_id'] = $id;
        } elseif ($type == 2) {
            $flowModel = new StaffFlowNew();
            $flowcopyModel = new StaffFlowCopy();
            $model = new Staff();
            $tixianModel = new StaffTixian();
            $where['staff_id'] = $id;
        }
        if ($type == 2) {
            $monthIncome = $flowModel->where('add_time', 'between', [$beginTime, $endTime])
                    ->where('type', 1)
                    ->where('status', 2)
                    ->where($where)
                    ->sum('money'); //本月营收
            $canSettled = $model->where('id', $id)->sum('money'); //可结算金额
            $tixianMoney = $tixianModel->where($where)->where('status', 'in', '0,1,2')->sum('money');
            $tixianPoundage = $tixianModel->where($where)->where('status', 'in', '0,1,2')->sum('poundage');
            $alreadySettled = $tixianMoney + $tixianPoundage; //已结算金额
        }

        //待提现金额
//        $time = time()- 7*24*60*60;
//        $noIncome = $flowcopyModel->where('add_time', '>', date('Y-m-d H:i:s',$time))
//                ->where('type', 1)
//                ->where($where)
//                ->sum('money'); 
        if($type == 1){
            $noIncome1 = $flowcopyModel->where('type',1)
                    ->where('pro_type','in','1,2,3,4,5,7,8,9,15')
                    ->where($where)
                    ->sum('money');
            $noIncome2 = $flowcopyModel->where('pro_type','in','11,14')
                    ->where($where)
                    ->sum('money');
        }  else {
            $noIncome1 = $flowModel->where('type',1)
                    ->where('pro_type','in','1,2,3,4,5,6,7')
                    ->where('status','in','0,1')
                    ->where($where)
                    ->sum('money');
            $noIncome2 = 0;
        }
        
        $noIncome = $noIncome1 - $noIncome2;
        //服务营收
        if ($type == 1) {
            $iteminsert = $flowModel->where('type', '=', 1)
//                    ->where('status', 2)
                    ->where($where)
                    ->where('pro_type', 'in', '1,2,3,5,15,16')
                    ->sum('money');
//            $itemrefunt = $flowModel
////                    ->where('type', '=', 2)
//                    ->where($where)
//                    ->where('pro_type', '=', 6)
//                    ->sum('money');
            $itemMoney = $iteminsert - 0; //项目营收
        } else {//美容师
            $iteminsert = $flowModel->where('type', '=', 1)
                    ->where('status', 2)
                    ->where($where)
                    ->where('pro_type', 'in', '1,2,3,5,15')
                    ->sum('money');
//            $itemrefunt = $flowModel->where('type', '=', 1)
//                    ->where('status', 3)
//                    ->where($where)
//                    //->where('pro_type', '=', 6)
//                    ->sum('money');
            $itemMoney = $iteminsert - 0; //项目营收
        }

        //商品营收
        if($type == 1){
            $goodsMoney = $flowModel->where('type', '=', 1)
                //->where('status',2)
                ->where($where)
                ->where('pro_type', 'in', '7,11')
                ->sum('money');
        }  else {
            $goodsMoney = $flowModel->where('type', '=', 1)
                ->where('status',2)
                ->where($where)
                ->where('pro_type', 'in', '6,7')
                ->sum('money');
        }
        
        //特权营收
        if($type == 1){
            $specialMoney = $flowModel->where('type', '=', 1)
                //->where('status',2)
                ->where($where)
                ->where('pro_type', 'in', '4,9')
                ->sum('money');
        }  else {
            $specialMoney = $flowModel->where('type', '=', 1)
                ->where('status',2)
                ->where($where)
                ->where('pro_type', 'in', '4')
                ->sum('money');
        }
        
        //体验卡营收
        if($type == 1){//1店铺2美容师
            $cardMoney = $flowModel->where('type', '=', 1)
                //->where('status',2)
                ->where($where)
                ->where('pro_type', 'in', '20,21')
                ->sum('money');
        }  else {
            $cardMoney = $flowModel->where('type', '=', 1)
                ->where('status',2)
                ->where($where)
                ->where('pro_type', 'in', '20,21')
                ->sum('money');
        }
        
        if($type == 1){
            $ApiPath = config('appconfig.ApiPath8890');
            $relust = Utils::curlPost1($ApiPath . '/store/toPhpStoreFundManagemenTotle/'.$id);
            $relust = json_decode($relust,true);
            $monthIncome = $relust['data']['transMoneyAll'];
            $canSettled = $relust['data']['canUserMoney'];
            $alreadySettled = $relust['data']['txMoney'];
            $noIncome = $relust['data']['waitMoney'];
        }
        
        $data['monthIncome'] = $monthIncome;//本月营收  =>  交易金额
        $data['canSettled'] = $canSettled;//可结算金额  =>  可提现金额
        $data['alreadySettled'] = $alreadySettled;//已结算金额  => 已累计提现
        $data['itemMoney'] = $itemMoney;
        $data['goodsMoney'] = $goodsMoney;
        $data['specialMoney'] = $specialMoney;
        $data['cardMoney'] = $cardMoney;
        $data['noIncome'] = $noIncome;//待提现金额
        return $this->ajaxReturn(0, '查询成功', $data);
    }

    /*
     * 项目明细账单
     * author xfwed
     * date 2019-09-26
     * */

    public function itemBillDetails() {
        $type = input('param.type'); //1店铺2美容师
        $id = input('param.id'); //店铺id/美容师id
        $perPage = input('param.perPage');
        $page = input('param.page');
        $pro_type = input('param.pro_type');
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        if ($type == 1) {
            $flowModel = new StoreFlow();
            $model = new Store();
            $tixianModel = new StoreTixian();
            $where['f.store_id'] = $id;
            if($pro_type){
                $where['f.pro_type'] = $pro_type;
            }  else {
                $where['f.pro_type'] = ['in', '1,2,5,15'];
            }
        } elseif ($type == 2) {
            $flowModel = new StaffFlowNew();
            $model = new Staff();
            $tixianModel = new StaffTixian();
            $where['f.staff_id'] = $id;
            $where['f.status'] = 2;
            if($pro_type){
                $where['f.pro_type'] = $pro_type;
            }  else {
                $where['f.pro_type'] = ['in', '1,2,5,15'];//流水类型 类型 1项目 2超值组合 3充值 4 特权卡5秒杀 6项目退款 7 商品 8提现 9体验特权 10商品退款	
            }
        }
        
        
        if ($end_time && $start_time) {
            $where['f.add_time'] = array('between', array($start_time, $end_time));
        } elseif (empty($end_time) && $start_time) {
            $time = strtotime($start_time);
            $time2 = $time + 24 * 60 * 60;
            $time2 = date('Y-m-d H:i:s', $time2);
            $where['f.add_time'] = array('between', array($time, $time2));
        }
        //需要关联订单 美容师 用户 店铺
        $list = $flowModel->alias('f')
                ->join('yuyue y', 'y.id = f.order_id', 'left')
                ->join('order o', 'y.order_id = o.id', 'left')
                ->join('staff m', 'y.staff_id = m.id', 'left')
                ->join('custom c', 'y.ctm_id = c.id', 'left')
                ->join('store s', 'y.store_id = s.id', 'left')
                ->where($where)
                ->field('o.ord_num,o.pay_time,o.pay_money,o.balance_money,o.red_money,s.store_name,s.city,f.id,f.item_name,f.money,c.custom_name,m.staff_name')
                ->paginate($perPage);
        foreach ($list as $k => $v) {
            $list[$k]['cityName'] = ProvCityArea::cityName($v['city']);
        }

        return $this->ajaxReturn(0, '查询成功', $list);
    }
    
    /*
     * 特权明细账单
     * author xfwed
     * date 2020-04-20
     * */

    public function specialBillDetails() {
        $type = input('param.type'); //1店铺2美容师
        $id = input('param.id'); //店铺id
        $perPage = input('param.perPage');
        $page = input('param.page');
        $pro_type = input('param.pro_type');
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        if ($type == 1) {
            $flowModel = new StoreFlow();
            $model = new Store();
            $tixianModel = new StoreTixian();
            $where['f.store_id'] = $id;
            if ($pro_type) {
                $where['f.pro_type'] = $pro_type;
            } else {
                $where['f.pro_type'] = ['in', '4,9'];
            }
        } elseif ($type == 2) {
            $flowModel = new StaffFlowNew();
            $where['f.staff_id'] = $id;
            if ($pro_type) {
                $where['f.pro_type'] = $pro_type;
            } else {
                $where['f.pro_type'] = 4;
            }
        }
        if ($end_time && $start_time) {
            $where['f.add_time'] = array('between', array($start_time, $end_time));
        } elseif (empty($end_time) && $start_time) {
            $time = strtotime($start_time);
            $time2 = $time + 24 * 60 * 60;
            $time2 = date('Y-m-d H:i:s', $time2);
            $where['f.add_time'] = array('between', array($time, $time2));
        }
        //需要关联订单 美容师 用户 店铺
        $list = $flowModel->alias('f')
                ->join('order o', 'f.order_id = o.id', 'left')
                ->join('custom c', 'o.ctm_id = c.id', 'left')
                ->join('store s', 'o.store_id = s.id', 'left')
                ->where($where)
                ->field('o.ord_num,o.pay_time,o.pay_money,o.balance_money,o.red_money,s.store_name,s.city,f.id,f.item_name,f.money,c.custom_name')
                ->paginate($perPage);
        foreach ($list as $k => $v) {
            $list[$k]['cityName'] = ProvCityArea::cityName($v['city']);
        }

        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 商品明细账单
     * author xfwed
     * date 2019-09-26
     * */

    public function goodsBillDetails() {
        $type = input('param.type'); //1店铺2美容师3厂家
        $id = input('param.id'); //店铺id/美容师id/品牌id
        $perPage = input('param.perPage');
        $page = input('param.page');
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        if ($type == 1) {
            $flowModel = new StoreFlow();
            $where['f.store_id'] = $id;
            $where['f.pro_type'] = ['in','7,11'];
        } elseif ($type == 2) {
            $flowModel = new StaffFlowNew();
            $where['f.staff_id'] = $id;
            $where['f.pro_type'] = ['in','6,7'];
            $where['f.status'] = 2;
        } elseif ($type == 3) {
            $flowModel = new VenderFlow();
            $where['f.brand_id'] = $id;
            $where['f.pro_type'] = ['in','7,9'];
        }
        if ($end_time && $start_time) {
            $where['o.pay_time'] = array('between', array($start_time, $end_time));
        } elseif (empty($end_time) && $start_time) {
            $time = strtotime($start_time);
            $time2 = $time + 24 * 60 * 60;
            $time2 = date('Y-m-d H:i:s', $time2);
            $where['o.pay_time'] = array('between', array($time, $time2));
        }
        $list = $flowModel->alias('f')
                 ->join(['pay_order_goods' => 'g'],'g.id = f.order_id','left')
                 ->join(['pay_order_detail'=>'o'],'o.id = g.pay_order_id','left')
                ->join('custom c', 'o.ctm_id = c.id', 'left')
                ->join('store s', 'o.store_id = s.id', 'left')
                //->join(['pay_order_detail'=> 'p'],'p.order_id = o.order_id','left')
                ->where($where)
                ->field('o.id,o.store_id,o.order_id,o.pay_money,o.pay_time,o.brand_id,c.custom_name,s.store_name,f.money')
                ->paginate($perPage);
        foreach ($list as $k => $v) {
            //查询售货机编号
            $list[$k]['robot_no'] = Db::table('da_machine_store_relation')
                    ->where('store_id', $v['store_id'])
                    ->where('machine_type', 1)
                    ->value('robot_no');
            //查询订单品牌
            $list[$k]['brandName'] = Db::table('brand_info')
                    ->where('id', 'in', $v['brand_id'])
                    ->value('name');
            //查询商品名
            $list[$k]['goodsName'] = Db::table('pay_order_goods')
                    ->where('pay_order_id', '=', $v['id'])
                    ->column('name');
        }

        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 厂家提现列表
     * author xfwed 
     * date 2019.09.26
     */

    public function venderTixianList() {
        $type = input('param.type'); //1未结算2已结算
        $brand_id = input('param.brand_id'); //品牌id
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');

        $perPage = input('param.perPage');
        $page = input('param.page');

        if ($end_time && $start_time) {
            if ($type == 1) {
                $where['t.add_time'] = array('between', array($start_time, $end_time));
            } elseif ($type == 2) {
                $where['t.utime'] = array('between', array($start_time, $end_time));
            }
        } elseif (empty($end_time) && $start_time) {
            $time = strtotime($start_time);
            $time2 = $time + 24 * 60 * 60;
            $time2 = date('Y-m-d H:i:s', $time2);
            if ($type == 1) {
                $where['t.add_time'] = array('between', array($time, $time2));
            } elseif ($type == 2) {
                $where['t.utime'] = array('between', array($time, $time2));
            }
        }
        if ($type == 1) {
            $where['t.status'] = $type;
            $order = 't.add_time asc';
        } elseif ($type == 2) {
            $where['t.status'] = $type;
            $order = 't.utime desc';
        }
        
        if($brand_id){
            $where['b.id'] = $brand_id;
        }

        $where['t.status'] = $type;
        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        $list = VenderTixian::alias('t')
                ->join(['brand_info' => 'b'], 'b.id = t.brand_id', 'left')
                ->field('t.*,b.name')
                ->order($order)
                ->where($where)
                ->paginate($perPage);

        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 厂家财务汇总
     * author xfwed
     * date 2019-09-27
     * */

    public function venderFinanceInfo() {
        $id = input('param.id'); //品牌id
        $flowModel = new VenderFlow();

        $allmoney1 = $flowModel->where('brand_id', $id)->where('type',1)->sum('money'); //总金额
        $allmoney2 = $flowModel->where('brand_id', $id)->where('pro_type',6)->sum('money'); //退款金额
        $tixianMoney = VenderTixian::where('brand_id', $id)->where('status', '=', '1')->sum('money');
        $tixianPoundage = VenderTixian::where('brand_id', $id)->where('status', '=', '1')->sum('poundage');
        $tixianMoney1 = VenderTixian::where('brand_id', $id)->where('status', '=', '2')->sum('money');
        $tixianPoundage1 = VenderTixian::where('brand_id', $id)->where('status', '=', '2')->sum('poundage');
        $noSettled = $tixianMoney + $tixianPoundage; //未结算金额
        $alreadySettled = $tixianMoney1 + $tixianPoundage1; //已结算金额
        $canSettled = $allmoney1-$allmoney2-$noSettled-$alreadySettled;//可结算

        $data['canSettled'] = $canSettled;
        $data['noSettled'] = $noSettled;
        $data['alreadySettled'] = $alreadySettled;
        $data['price'] = $allmoney1-$allmoney2;
        return $this->ajaxReturn(0, '查询成功', $data);
    }

    /*
     * 厂家结算
     * author xfwed
     * date 2019-09-27
     * */

    public function venderBalance() {
        $id = input('param.id');
        $tadmin = input('param.tadmin');
        if (empty($tadmin)) {
            return Utils::ajaxReturn(3, '提现管理员不能为空', null);
        }
        $tixian = new VenderTixian();
        $data['tadmin'] = $tadmin;
        $data['status'] = 2;
        $data['utime'] = date('Y-m-d H:i:s');

        $row = $tixian->where('id', '=', $id)->find();
        if ($row['status'] == 2) {
            return Utils::ajaxReturn(3, '已经结算啦！', null);
        }

        $result = $tixian->where('id', '=', $id)->update($data);
        if ($result) {
            return Utils::ajaxReturn(0, "结算成功", null);
        } else {
            return Utils::ajaxReturn(3, '结算失败', null);
        }
    }

    /*
     * 财务管理汇总（总）
     * author xfwed 
     * date 2019.10.09
     */

    public function financeList() {
        $type = input('param.type'); //1项目2商品
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');

        $perPage = input('param.perPage');
        $page = input('param.page');
        $store_type = input('param.store_type');//店铺类型 0全部 1品牌连锁店 2服务授权店

        if ($end_time && $start_time) {
            $time = $start_time;
            $time2 = $end_time;
            $where['add_time'] = array('between', array($time, $time2));
            $where1['s.add_time'] = array('between', array($time, $time2));
        } elseif (empty($end_time) && $start_time) {
            $time = strtotime($start_time);
            $time2 = $time + 24 * 60 * 60;
            $time2 = date('Y-m-d H:i:s', $time2);
            $where['add_time'] = array('between', array($time, $time2));
            $where1['s.add_time'] = array('between', array($time, $time2));
        }
        if($store_type){
            $where1['st.type'] = $store_type;
        }

        $where = isset($where) ? $where : [];
        $where1 = isset($where1) ? $where1 : [];
        //总账单
        $itemMoney = StoreFlow::where('type', 1)
                ->where('pro_type', 'in', '1,2,3,4,5,15')
                ->where($where)
                ->group('order_id')
                ->sum('allmoney');
        $goodsMoney = StoreFlow::where('type', 1)
                ->where('pro_type', '=', 7)
                ->where($where)
                ->group('order_id')
                ->sum('allmoney');
        $data['itemMoney'] = $itemMoney;
        $data['goodsMoney'] = $goodsMoney;
        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;


        if ($type == 1) {
            //项目营收
            $list = StoreFlow::alias('s')
                    ->join('yuyue y', 'y.id = s.order_id', 'left')
                    ->join('order o', 'y.order_id = o.id', 'left')
                    ->join('store st', 'st.id = s.store_id', 'left')
                    ->where('s.type', 1)
                    ->where('s.pro_type', 'in', '1,2,3,5,15')
                    ->where($where1)
                    ->order('s.id desc')
                    ->field('o.ord_num,st.store_name,st.type store_type,s.add_time,s.allmoney,s.pro_type,s.id')
                    ->paginate($perPage);
        } elseif ($type == 2) {
            //商品营收
            $list = StoreFlow::alias('s')
                    ->join(['pay_order_detail' => 'o'], 'o.id = s.order_id', 'left')
                    ->join('store st', 'st.id = s.store_id', 'left')
                    ->where('s.type', 1)
                    ->where('s.pro_type', 'in', '7,11')
                    ->where($where1)
                    ->order('s.id desc')
                    ->field('o.order_id as ord_num,st.store_name,st.type store_type,s.add_time,s.allmoney,s.pro_type,s.id')
                    ->paginate($perPage);
        }
        $data['list'] = $list;
        return $this->ajaxReturn(0, '查询成功', $data);
    }

    /* 导出厂家未结算账单
     * author xfwed
     * date 2019-10-10
     */

    public function venderTixianExcel() {
        $type = input('param.type'); //1未结算2已结算
        $brand_id = input('param.brand_id'); //品牌id
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');

        if ($end_time && $start_time) {
            if ($type == 1) {
                $where['t.add_time'] = array('between', array($start_time, $end_time));
            } elseif ($type == 2) {
                $where['t.utime'] = array('between', array($start_time, $end_time));
            }
        } elseif (empty($end_time) && $start_time) {
            $time = strtotime($start_time);
            $time2 = $time + 24 * 60 * 60;
            $time2 = date('Y-m-d H:i:s', $time2);
            if ($type == 1) {
                $where['t.add_time'] = array('between', array($time, $time2));
            } elseif ($type == 2) {
                $where['t.utime'] = array('between', array($time, $time2));
            }
        }
        if ($type == 1) {
            $where['t.status'] = $type;
            $order = 't.add_time asc';
            $expTitle = '厂家未提现账单';
        } elseif ($type == 2) {
            $where['t.status'] = $type;
            $order = 't.utime desc';
            $expTitle = '厂家已提现账单';
        }

        $where['t.status'] = $type;
        $expTableData = VenderTixian::alias('t')
                ->join(['brand_info' => 'b'], 'b.id = t.brand_id', 'left')
                ->field('t.*,b.name')
                ->order($order)
                ->where($where)
                ->select();

        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle . '(-共计' . count($expTableData) . '条)'); //文件名称
        $fileName = $xlsTitle; //or $xlsTitle 文件名称可根据自己情况设定
        if (empty($expTableData)) {
            Utils::ajaxReturn(3, '没有未提现的账单', $data);
        }
        $ii = 3;
        Vendor('PHPExcel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[8 - 1] . '1'); //合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle . '  Export time:' . date('Y-m-d H:i:s'));
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(18);
        $objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray(//居中加粗
                array(
                    'font' => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
        );
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(30); // 第一行的默认高度
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(25); // 第一行的默认高度
        $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(20); // 所有单元格默认高度
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20); //设置宽width
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER); //垂直居中
        $objPHPExcel->getActiveSheet()->getStyle('2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER); //垂直居中
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的  
                    'style' => \PHPExcel_Style_Border::BORDER_THIN, //细边框  
                //'color' => array('argb' => 'FFFF0000'),  
                ),
            ),
        );
        $objPHPExcel->getActiveSheet()->getStyle('A1:H' . (count($expTableData) + 2))->applyFromArray($styleArray); //这里就是画出从单元格A5到N5的边框，看单元格最右边在哪哪个格就把这个N改为那个字母替代  


        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A2', "品牌名称");
        $objPHPExcel->getActiveSheet()->getStyle('A2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B2', "到账金额");
        $objPHPExcel->getActiveSheet()->getStyle('B2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C2', "手续费");
        $objPHPExcel->getActiveSheet()->getStyle('C2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D2', "银行名称");
        $objPHPExcel->getActiveSheet()->getStyle('D2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E2', "开户行地址");
        $objPHPExcel->getActiveSheet()->getStyle('E2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F2', "开户名");
        $objPHPExcel->getActiveSheet()->getStyle('F2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('G2', "卡号");
        $objPHPExcel->getActiveSheet()->getStyle('G2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('H2', "注册时间");
        $objPHPExcel->getActiveSheet()->getStyle('H2')->applyFromArray(array('font' => array('bold' => true)));

        foreach ($expTableData as $key => $val) {
            $tt = 'A' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['name']); //加  “ ”防止用科学计数法，中间必须有空格，否则无效
            $tt = 'B' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['money']/100);
            $tt = 'C' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['poundage']/100);
            $tt = 'D' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['bank_name']);
            $tt = 'E' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['bank_address']);
            $tt = 'F' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['bank_username']);
            $tt = 'G' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " ".$val['bank_num']);
            $tt = 'H' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['add_time']);
            $ii++;
        }
        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '.xls"');  //日期为文件名后缀
        header('Cache-Control: max-age=0');
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Pragma: no-cache");
        header("Expires: 0");
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
    
    /*
     * 小店商品明细账单
     * author xfwed
     * date 2020-05-12
     * */

    public function smallStoreGoodsBillDetails() {
        $type = input('param.type'); //1店铺
        $id = input('param.id'); //店铺id
        $perPage = input('param.perPage');
        $page = input('param.page');
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        if ($type == 1) {
            $flowModel = new StoreFlow();
            $where['f.store_id'] = $id;
            $where['f.pro_type'] = 11;
        } 
        if ($end_time && $start_time) {
            $where['o.pay_time'] = array('between', array($start_time, $end_time));
        } elseif (empty($end_time) && $start_time) {
            $time = strtotime($start_time);
            $time2 = $time + 24 * 60 * 60;
            $time2 = date('Y-m-d H:i:s', $time2);
            $where['o.pay_time'] = array('between', array($time, $time2));
        }
        $list = $flowModel->alias('f')
                ->join(['pay_order_detail' => 'o'], 'f.order_id = o.id', 'left')
                ->join('custom c', 'o.ctm_id = c.id', 'left')
                ->join('store s', 'o.store_id = s.id', 'left')
                //->join(['pay_order_detail'=> 'p'],'p.order_id = o.order_id','left')
                ->where($where)
                ->field('o.id,o.store_id,o.order_id,o.pay_money,o.pay_time,o.brand_id,o.mini_shop_id,c.custom_name,s.store_name,f.money')
                ->paginate($perPage);
        foreach ($list as $k => $v) {
            //查询售货机编号
            $list[$k]['robot_no'] = Db::table('da_machine_store_relation')
                    ->where('store_id', $v['store_id'])
                    ->where('machine_type', 1)
                    ->value('robot_no');
            //查询订单品牌
            $list[$k]['brandName'] = Db::table('brand_info')
                    ->where('id', 'in', $v['brand_id'])
                    ->value('name');
            //查询商品名
            $list[$k]['goodsName'] = Db::table('pay_order_goods')
                    ->where('pay_order_id', '=', $v['id'])
                    ->column('name');
            //查询小店店主名
            $list[$k]['mini_shop_name'] = Db::table('ai_custom')
                    ->where('id', '=', $v['mini_shop_id'])
                    ->column('custom_name');
        }

        return $this->ajaxReturn(0, '查询成功', $list);
    }
    
    /*
     * 用户提现列表
     * author xfwed 
     * date 2020.06.22
     */

    public function ctmTixianList() {
        $type = input('param.type');//1提现申请 2初审通过 3复审通过 4审核失败  	
        $ctm_name = input('param.ctm_name');
        $phone = input('param.phone');
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');

        $perPage = input('param.perPage');
        $page = input('param.page');

        if ($ctm_name) {
            $where['c.custom_name'] = ['like', '%' . $ctm_name . '%'];
        }

        if ($phone) {
            $where['c.custom_phone'] = $phone;
        }

        if ($end_time && $start_time) {
            if ($type == 1) {
                $where['t.add_time'] = array('between', array($start_time, $end_time));
            } elseif ($type == 2) {
                $where['t.one_time'] = array('between', array($start_time, $end_time));
            } elseif ($type == 3) {
                $where['t.two_time'] = array('between', array($start_time, $end_time));
            }elseif ($type == 4) {
                $where['t.fail_time'] = array('between', array($start_time, $end_time));
            }
        } elseif (empty($end_time) && $start_time) {
            $time = strtotime($start_time);
            $time2 = $time + 24 * 60 * 60;
            $time2 = date('Y-m-d H:i:s', $time2);
            if ($type == 1) {
                $where['t.add_time'] = array('between', array($time, $time2));
            } elseif ($type == 2) {
                $where['t.one_time'] = array('between', array($time, $time2));
            } elseif ($type == 3) {
                $where['t.two_time'] = array('between', array($time, $time2));
            }elseif ($type == 4) {
                $where['t.fail_time'] = array('between', array($time, $time2));
            }
        }
        if ($type == 1) {
            $order = 't.add_time asc';
        } elseif ($type == 2) {
            $order = 't.one_time asc';
        } elseif ($type == 3) {
            $order = 't.two_time desc';
        }elseif ($type == 4) {
            $order = 't.fail_time desc';
        }

        $where['t.status'] = $type;
        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        $list = CtmTixian::alias('t')
                ->join('custom c', 'c.id = t.ctm_id')
                ->field('t.*,c.custom_phone,c.custom_name')
                ->order($order)
                ->where($where)
                ->paginate($perPage);

        return $this->ajaxReturn(0, '查询成功', $list);
    }
    
    /*
     * 用户提现审核
     * author xfwed
     * date 2020-06-22
     * */

    public function auditCtmTixian() {
        $rule = [
            'id' => 'require',
            'type' => 'require',
            'name' => 'require',
        ];
        $msg = [
            'id.require' => 'id必须',
            'type.require' => '分类必须',
            'name.require' => '审核者必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }
        
        $id = input('param.id');
        $type = input('param.type');//1初审通过 2复审通过 3提现失败
        $name = input('param.name');
        $row = CtmTixian::where('id',$id)->find();
        if(empty($row)){
            return Utils::ajaxReturn(3, 'id错误', null);
        }
        if ($type == 1) {
            if($row['status'] != 1){
                return Utils::ajaxReturn(3, '数据有误，不需要审核', null);
            }
            $data['one_time'] = date('Y-m-d H:i:s');
            $data['one_name'] = $name;
            $data['status'] = 2;
            $result = CtmTixian::where('id',$id)->update($data);
            if($result){
                return Utils::ajaxReturn(0, '审核成功', null);
            }  else {
                return Utils::ajaxReturn(3, '审核失败', null);
            }
        } elseif ($type == 2) {
            if($row['status'] == 2){
                $ApiPath = config('appconfig.ApiPath');
                $postFields['batch'] = $row['batch'];
                $postFields['twoName'] = $name;
                $relust = Utils::curlPost($ApiPath . 'withdrawals/toWxCashWithdrawal', json_encode($postFields));
                $relust = json_decode($relust,true);
                if($relust['code'] == 0){
                    return Utils::ajaxReturn(0, '提现成功', null);
                }  else {
                    return Utils::ajaxReturn(3, '提现失败 退回余额', $relust);
                }
            }  else {
                return Utils::ajaxReturn(3, '初审通过才可以复审', null);
            }
        }elseif ($type == 3) {
            Db::startTrans(); //开启事务
            $data['fail_time'] = date('Y-m-d H:i:s');
            $data['fail_name'] = $name;
            $data['status'] = 4;
            //修改提现
            $tixianResult = CtmTixian::where('id',$id)->update($data);
            $real_money = $row['money'] + $row['poundage'];
            //用户余额返回
            $ctmResult = Custom::where('id',$row['ctm_id'])->setInc('real_money',$real_money);
            //插入一条流水
            $flowData['order_id'] = $row['id'];
            $flowData['item_name'] = '提现失败';
            $flowData['type'] = 1;
            $flowData['pro_type'] = 4;
            $flowData['ctm_id'] = $row['ctm_id'];
            $flowData['money'] = $row['money'] + $row['poundage'];
            $last_money = CtmFlow::where('ctm_id',$row['ctm_id'])->order('id desc')->value('last_money');
            $flowData['last_money'] = $last_money + $row['money'] + $row['poundage'];
            $flowData['add_time'] = date('Y-m-d H:i:s');
            $flowResult = CtmFlow::insert($flowData);
            if ($tixianResult && $ctmResult && $flowResult) {
                Db::commit();
                //$content = "温馨提示：由于您提供的支付宝账号有误，导致提现失败，请及时联系客服，提供正确的支付宝账号，重新提现，谢谢配合！如有疑问请联系客服 电话：4008013680";
                //$sendResult = Utils::sendSms($telephone, $content);
                return Utils::ajaxReturn(0, "审核成功", '');
            } else {
                Db::rollback(); //事务回滚
                return Utils::ajaxReturn(3, '审核失败', '');
            }
        }
    }
    
    /*
     * 交易笔数
     * author xfwed
     * date 2020-08-13
     * @param storeId
     * @param type 0.全部 1.项目 2.商品 3.特权 4.小店 5.退款退货
     * @param dateType 0.本日 1.本周 2.本月 3.全部 4.自定义
     * */

    public function getTransNumList() {
        $type = input('param.type'); //0.全部 1.项目 2.商品 3.特权 4.小店 5.退款退货
        $storeId = input('param.id'); //店铺id
        $perPage = input('param.perPage');
        $page = input('param.page');
        $dateType = input('param.dateType');
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        
        $ApiPath = config('appconfig.ApiPath8890');
            $postFields['storeId'] = $storeId; 
            $postFields['type'] = $type; 
            $postFields['dateType'] = $dateType;
            $postFields['startDate'] = $start_time;
            $postFields['endDate'] = $end_time;

            $relust = Utils::curlPost1($ApiPath . 'store/getTransNumList/'.$page.'/'.$perPage, $postFields);
        return $relust;
    }

    /*
     * 资金管理
     * author xfwed
     * date 2020-08-13
     * @param storeId
     * @param fundtype 0总交易， 1待入账，2入账中，3已入账  10待入账+入账中
     * @param type 0.全部 1.项目 2.商品 3.退款退货 4.特权 5.i美优优
     * @param dateType 0.本日 1.本周 2.本月 3.全部 4.自定义
     * */

    public function getFundManagemenList() {
        $type = input('param.type'); //0.全部 1.项目 2.商品 3.退款退货 4.特权 5.i美优优
        $storeId = input('param.id'); //店铺id
        $fundtype = input('param.fundtype'); 
        $perPage = input('param.perPage');
        $page = input('param.page');
        $dateType = input('param.dateType');
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        
        $ApiPath = config('appconfig.ApiPath8890');
            $postFields['storeId'] = $storeId; 
            $postFields['fundtype'] = $fundtype; 
            $postFields['type'] = $type; 
            $postFields['dateType'] = $dateType;
            $postFields['startDate'] = $start_time;
            $postFields['endDate'] = $end_time;

            $relust = Utils::curlPost1($ApiPath . 'store/getFundManagemenList/'.$page.'/'.$perPage, $postFields);
        return $relust;
    }
    
    /* 导出厂家商品明细账单
     * author xfwed
     * date 2020-09-22
     */

    public function venderGoodsBillDetailsExcel() {
        $type = 3; //1店铺2美容师3厂家
        $id = input('param.id'); //店铺id/美容师id/品牌id
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');

        $flowModel = new VenderFlow();
        $where['f.brand_id'] = $id;
        $where['f.pro_type'] = ['in','7,9'];
        
        if ($end_time && $start_time) {
            $where['o.pay_time'] = array('between', array($start_time, $end_time));
        } elseif (empty($end_time) && $start_time) {
            $time = strtotime($start_time);
            $time2 = $time + 24 * 60 * 60;
            $time2 = date('Y-m-d H:i:s', $time2);
            $where['o.pay_time'] = array('between', array($time, $time2));
        }
        $expTableData = $flowModel->alias('f')
                ->join(['pay_order_detail' => 'o'], 'f.order_id = o.id', 'left')
                ->join('custom c', 'o.ctm_id = c.id', 'left')
                ->join('store s', 'o.store_id = s.id', 'left')
                ->where($where)
                ->field('o.id,o.store_id,o.order_id,o.pay_money,o.pay_time,o.brand_id,c.custom_name,s.store_name,f.money')
                ->select();
        foreach ($expTableData as $k => $v) {
            //查询售货机编号
            $expTableData[$k]['robot_no'] = Db::table('da_machine_store_relation')
                    ->where('store_id', $v['store_id'])
                    ->where('machine_type', 1)
                    ->value('robot_no');
            //查询订单品牌
            $expTableData[$k]['brandName'] = Db::table('brand_info')
                    ->where('id', 'in', $v['brand_id'])
                    ->value('name');
            //查询商品名
            $expTableData[$k]['goodsName'] = Db::table('pay_order_goods')
                    ->where('pay_order_id', '=', $v['id'])
                    ->column('name');
        }

        $expTitle = '厂家商品明细账单';
        
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle . '(-共计' . count($expTableData) . '条)'); //文件名称
        $fileName = $xlsTitle; //or $xlsTitle 文件名称可根据自己情况设定
        if (empty($expTableData)) {
            Utils::ajaxReturn(3, '没有相关的账单', null);
        }
        $ii = 3;
        Vendor('PHPExcel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[8 - 1] . '1'); //合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle . '  Export time:' . date('Y-m-d H:i:s'));
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(18);
        $objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray(//居中加粗
                array(
                    'font' => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
        );
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(30); // 第一行的默认高度
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(25); // 第一行的默认高度
        $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(20); // 所有单元格默认高度
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20); //设置宽width
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER); //垂直居中
        $objPHPExcel->getActiveSheet()->getStyle('2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER); //垂直居中
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的  
                    'style' => \PHPExcel_Style_Border::BORDER_THIN, //细边框  
                //'color' => array('argb' => 'FFFF0000'),  
                ),
            ),
        );
        $objPHPExcel->getActiveSheet()->getStyle('A1:G' . (count($expTableData) + 2))->applyFromArray($styleArray); //这里就是画出从单元格A5到N5的边框，看单元格最右边在哪哪个格就把这个N改为那个字母替代  


        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A2', "品牌名称");
        $objPHPExcel->getActiveSheet()->getStyle('A2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B2', "店铺名称");
        $objPHPExcel->getActiveSheet()->getStyle('B2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C2', "订单编号");
        $objPHPExcel->getActiveSheet()->getStyle('C2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D2', "产品名称");
        $objPHPExcel->getActiveSheet()->getStyle('D2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E2', "付款时间");
        $objPHPExcel->getActiveSheet()->getStyle('E2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F2', "下单用户");
        $objPHPExcel->getActiveSheet()->getStyle('F2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('G2', "入账金额");
        $objPHPExcel->getActiveSheet()->getStyle('G2')->applyFromArray(array('font' => array('bold' => true)));
        

        foreach ($expTableData as $key => $val) {
            $tt = 'A' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['brandName']); //加  “ ”防止用科学计数法，中间必须有空格，否则无效
            $tt = 'B' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['store_name']);
            $tt = 'C' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['order_id']);
            $tt = 'D' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, implode($val['goodsName']));
            $tt = 'E' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['pay_time']);
            $tt = 'F' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['custom_name']);
            $tt = 'G' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " ".$val['money']/100);
            $ii++;
        }
        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '.xls"');  //日期为文件名后缀
        header('Cache-Control: max-age=0');
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Pragma: no-cache");
        header("Expires: 0");
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
    
    /*
     * 厂家提现订单列表
     * author xfwed 
     * date 2021.01.08
     */

    public function venderTixianOrderList() {
        $id = input('param.id');//提现id
        $order_id = input('param.order_id');

        $perPage = input('param.perPage');
        $page = input('param.page');

        if ($order_id) {
            $where['d.order_id'] = $order_id;
        }
        
        $order_ids = VenderTixian::where('id',$id)->value('order_ids');
        $where['d.id'] = ['in',$order_ids];
        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        
        $list = Db::table('pay_order_detail')
                ->alias('d')
                ->join('vender_flow v','v.order_id = d.id','left')
                ->where($where)
                ->field('d.id,d.order_id,d.name,d.phone,d.pay_money,d.pay_num,d.logistics_num,d.logistics_date,d.remark,d.status,d.pay_time,d.arrived_time,v.money')
                ->paginate($perPage);
        return $this->ajaxReturn(0, '查询成功', $list);
    }
    
    /*
     * 体验卡明细账单
     * author xfwed
     * date 2021-06-03
     * */

    public function cardBillDetails() {
        $type = input('param.type'); //1店铺2美容师
        $id = input('param.id'); //店铺id
        $perPage = input('param.perPage');
        $page = input('param.page');
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        if ($type == 1) {
            $flowModel = new StoreFlow();
            $where['f.store_id'] = $id;
            $where['f.pro_type'] = ['in', '20,21'];
        } elseif ($type == 2) {
            $flowModel = new StaffFlowNew();
            $where['f.staff_id'] = $id;
            $where['f.pro_type'] = ['in', '20,21'];
        }
        if ($end_time && $start_time) {
            $where['f.add_time'] = array('between', array($start_time, $end_time));
        } elseif (empty($end_time) && $start_time) {
            $time = strtotime($start_time);
            $time2 = $time + 24 * 60 * 60;
            $time2 = date('Y-m-d H:i:s', $time2);
            $where['f.add_time'] = array('between', array($time, $time2));
        }
        //需要关联订单 美容师 用户 店铺
        if($type == 1){//1店铺2美容师
            $list = $flowModel->alias('f')
                ->join('super_card_order o', 'f.order_id = o.id and f.pro_type = 20', 'left')
                ->join('super_card_yuyue y','f.order_id = y.id and f.pro_type = 21','left')
                ->join('super_card_order o1', 'y.order_id = o1.id', 'left')
                ->join('custom c', 'o.ctm_id = c.id', 'left')
                ->join('custom c1', 'o1.ctm_id = c1.id', 'left')
                ->where($where)
                ->field('if(f.pro_type =20,o.order_no,o1.order_no) as ord_num,'
                        .'if(f.pro_type =20,o.pay_time,o1.pay_time) as pay_time,'
                        .'if(f.pro_type =20,o.pay_money,o1.pay_money) as pay_money,'
                        .'if(f.pro_type =20,o.balance_money,o1.balance_money) as balance_money,'
                        .'if(f.pro_type =20,o.red_money,o1.red_money) as red_money,'
                        .'if(f.pro_type =20,c.custom_name,c1.custom_name) as custom_name,'
                        .'f.id,f.item_name,f.money,c.custom_name')
                ->paginate($perPage);

        }elseif ($type == 2) {
            $list = $flowModel->alias('f')
                ->join('super_card_order o', 'f.order_id = o.id and f.pro_type = 20', 'left')
                ->join('super_card_yuyue y','f.order_id = y.id and f.pro_type = 21','left')
                ->join('super_card_order o1', 'y.order_id = o1.id', 'left')
                ->join('custom c', 'o.ctm_id = c.id', 'left')
                ->join('custom c1', 'o1.ctm_id = c1.id', 'left')
                ->where($where)
                ->where('f.status',2)
                ->field('if(f.pro_type =20,o.order_no,o1.order_no) as ord_num,'
                        .'if(f.pro_type =20,o.pay_time,o1.pay_time) as pay_time,'
                        .'if(f.pro_type =20,o.pay_money,o1.pay_money) as pay_money,'
                        .'if(f.pro_type =20,o.balance_money,o1.balance_money) as balance_money,'
                        .'if(f.pro_type =20,o.red_money,o1.red_money) as red_money,'
                        .'if(f.pro_type =20,c.custom_name,c1.custom_name) as custom_name,'
                        .'f.id,f.item_name,f.money,c.custom_name')
                ->paginate($perPage);
        }

        return $this->ajaxReturn(0, '查询成功', $list);
    }
    
}
